/*
 * ProjectCreator.cpp
 *
 *  Created on: 2013-2-1
 *      Author: Dspark
 */

#include "ProjectCreator.h"

ProjectCreator::ProjectCreator(User& user, QWidget* parent):QWidget(parent),user(user),pid(0)
{
	initUI();
}

ProjectCreator::ProjectCreator(User& user, quint32 pid):user(user),pid(pid)
{
	initUI();
}

void ProjectCreator::initUI()
{
	this->setAttribute(Qt::WA_DeleteOnClose,true);
	lab_name.setText("项目名称");
	lab_startDate.setText("开始时间");
	lab_expDate.setText("预定结束时间");
	lab_totalBuget.setText("总预算额");
	lab_unit.setText("万元");
	input_finish.setText("是否完结");
	lab_comment.setText("项目概述");
	pid>0?submit.setText("更新"):submit.setText("创建项目");
	layout.addWidget(&lab_name,0,0);
	layout.addWidget(&input_name,0,1,1,7);

	input_startDate.setCalendarPopup(true);
	input_expDate.setCalendarPopup(true);
	input_startDate.setDate(QDate::currentDate());
	input_expDate.setDate(QDate::currentDate().addYears(1));

	layout.addWidget(&lab_totalBuget,1,0);
	layout.addWidget(&input_totalBuget,1,1);
	layout.addWidget(&lab_unit,1,2);
	layout.addWidget(&input_finish,1,3);
	layout.addWidget(&lab_startDate,1,4);
	layout.addWidget(&input_startDate,1,5);
	layout.addWidget(&lab_expDate,1,6);
	layout.addWidget(&input_expDate,1,7);

	layout.addWidget(&lab_comment,2,0);
	layout.addWidget(&input_comment,2,1,2,7);

	pid==0?managerSelector.load(user):managerSelector.load(pid);
	layout.addWidget(&managerSelector,4,0,4,8);

	layout.addWidget(&submit, 8, 3, 1, 2);
	this->setLayout(&layout);

	connect(&submit, SIGNAL(clicked()), this, SLOT(slt_saveProject()));
	this->setWindowModality(Qt::ApplicationModal);

	if(pid>0){
		setWindowTitle("修改项目信息");
		loadData(pid);
	}else{
		setWindowTitle("新建项目");
	}
}

void ProjectCreator::loadData(quint32 pid)
{
	QSqlQuery query(Dao.getDateBase());

	if( query.exec( QString(" select name,totalBuget,finished,description,startDate,expDate from project where id = %1 ").arg(pid) ) )
	{
		QSqlRecord r = query.record();
		if(query.next())
		{
			input_name.setText( query.value(r.indexOf("name")).toString() );
			input_totalBuget.setText( query.value(r.indexOf("totalBuget")).toString() );
			input_finish.setChecked( query.value(r.indexOf("finished")).toBool() );
			input_comment.setText( query.value(r.indexOf("description")).toString() );
			input_startDate.setDate( query.value(r.indexOf("startDate")).toDate()  );
			input_expDate.setDate( query.value(r.indexOf("expDate")).toDate()  );
		}else{
			qDebug()<<"No data queried";
		}
	}else{
		qDebug()<<pid<<" is not found!";
	}
}

bool ProjectCreator::isInvalid()
{
	bool invalid = false;
	QString alert;
	if(input_name.text().trimmed().isEmpty())
	{
		invalid = true;
		alert.append("请输入项目名\n");
	}

	if(managerSelector.getSelectedUserId().size()<1)
	{
		invalid = true;
		alert.append("请至少选择一名管理人员\n");
	}

	if(invalid)
	{
		QMessageBox::critical(this, "数据非法", alert);
	}

	return invalid;
}

void ProjectCreator::doUpdate()
{
	QSqlQuery sql(Dao.getDateBase());
	sql.prepare("UPDATE `project` SET "
	" `name` = :name,`totalBuget` = :totalBuget, `finished` = :finished, `description` = :description,"
	" `maker`= :maker,`startDate` = :startDate, `expDate` = :expDate, `finishDate` = :finishDate "
	"  where id = :id;"
	);
	sql.bindValue(":name", input_name.text());
	sql.bindValue(":totalBuget", input_totalBuget.text().toDouble());
	sql.bindValue(":finished", input_finish.isChecked());
	sql.bindValue(":description",input_comment.toPlainText());
	sql.bindValue(":maker",user.getId());
	sql.bindValue(":startDate",input_startDate.date());
	sql.bindValue(":expDate",input_expDate.date());
	sql.bindValue(":finishDate", QDate::currentDate());
	sql.bindValue(":id", pid);
	if(sql.exec())
	{
		qDebug()<<"Base Infor updated! Try to update managers";
		QList<quint32>& ids = managerSelector.getSelectedUserId();
		QString inserts(QString("DELETE FROM `user2proejct` where pid = %1;").arg(pid));
		foreach(quint32 id, ids)
		{
			inserts.append( QString("INSERT INTO `user2proejct`(`pid`,`uid`) VALUES(%1,%2);").arg(pid).arg(id) );
		}
		if(sql.exec(inserts))
		{
			QMessageBox::information(this,"提示","修改成功!");
			this->hide();
			emit sig_succeed();
			deleteLater();
		}else{
			qDebug()<<"Something wrong happend when insert ids";
			qDebug()<<sql.lastQuery();
			qDebug()<<sql.lastError().text();
			emit sig_fail();
		}
	}else{
		qDebug()<<"Base Infor update fail!";
		qDebug()<<sql.lastQuery();
		qDebug()<<sql.lastError().text();
	}
}
void ProjectCreator::doInsert()
{
	QSqlQuery sql(Dao.getDateBase());
	sql.prepare("INSERT INTO `project`"
		"(`name`,`totalBuget`,`finished`,`description`,`maker`,`startDate`,`expDate`,`createDate`)"
		"VALUES (:name,:totalBuget,:finished,:description,:maker,:startDate,:expDate,:createDate)"
	);
	sql.bindValue(":name", input_name.text());
	sql.bindValue(":totalBuget", input_totalBuget.text().toDouble());
	sql.bindValue(":finished",input_finish.isChecked());
	sql.bindValue(":description",input_comment.toPlainText());
	sql.bindValue(":maker",user.getId());
	sql.bindValue(":startDate",input_startDate.date());
	sql.bindValue(":expDate",input_expDate.date());
	sql.bindValue(":createDate",QDate::currentDate());

	if(sql.exec())
	{
		quint32 pid = sql.lastInsertId().toUInt();
		QList<quint32>& ids = managerSelector.getSelectedUserId();
		QString inserts;
		foreach(quint32 id, ids)
		{
			inserts.append( QString("INSERT INTO `user2proejct`(`pid`,`uid`) VALUES(%1,%2);").arg(pid).arg(id) );
		}
		qDebug()<<"插入的SQL代码：\n"<<inserts;
		if(sql.exec(inserts))
		{
			QMessageBox::information(this,"提示","添加成功!");
			this->hide();
			emit sig_succeed();
			deleteLater();
		}else{
			qDebug()<<"Something wrong happend when insert ids";
			emit sig_fail();
		}
	}else{
		qDebug()<<"Something wrong happened";
		QMessageBox::critical(this,"错误","保存到数据库失败！");
		emit sig_fail();
	}
}

void ProjectCreator::slt_saveProject()
{
	if(isInvalid())
	{
		return;
	}

	if(pid==0)
	{
		doInsert();
	}else{
		doUpdate();
	}
}

ProjectCreator::~ProjectCreator() {
	// TODO Auto-generated destructor stub
}

